import redis
import json
import time
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class RedisMonitor:
    def __init__(self):
        self.redis_config = {
            'host': '123.60.24.64',
            'port': 6379,
            'password': '@Ym19950928',
            'db': 0,
            'decode_responses': True,
            'socket_connect_timeout': 10,
            'socket_timeout': 10
        }

    def test_connection(self):
        """测试Redis连接"""
        try:
            r = redis.Redis(**self.redis_config)
            info = r.info()
            logging.info(f"Redis连接成功 - 版本: {info['redis_version']}, 内存使用: {info['used_memory_human']}")
            return True
        except Exception as e:
            logging.error(f"Redis连接失败: {e}")
            return False

    def check_channels(self):
        """检查频道信息"""
        try:
            r = redis.Redis(**self.redis_config)

            # 检查频道订阅者
            channels = ['jq_orders', 'jq_orders_backup']
            for channel in channels:
                num_sub = r.pubsub_numsub(channel)
                logging.info(f"频道 {channel} 订阅者数量: {num_sub[0][1]}")

            return True
        except Exception as e:
            logging.error(f"检查频道失败: {e}")
            return False

    def check_lists(self):
        """检查列表数据"""
        try:
            r = redis.Redis(**self.redis_config)

            list_keys = ['jq_orders_list', 'jq_orders_backup_list']
            for key in list_keys:
                length = r.llen(key)
                if length > 0:
                    # 查看最新的几条消息
                    messages = r.lrange(key, -5, -1)
                    logging.info(f"列表 {key} 有 {length} 条消息，最近5条:")
                    for i, msg in enumerate(messages):
                        try:
                            data = json.loads(msg)
                            logging.info(f"  {i + 1}. {data.get('security', 'N/A')} - {data.get('timestamp', 'N/A')}")
                        except:
                            logging.info(f"  {i + 1}. 无法解析: {msg}")
                else:
                    logging.info(f"列表 {key} 为空")

            return True
        except Exception as e:
            logging.error(f"检查列表失败: {e}")
            return False

    def check_zsets(self):
        """检查有序集合数据"""
        try:
            r = redis.Redis(**self.redis_config)

            zset_keys = ['jq_orders_zset']
            for key in zset_keys:
                count = r.zcard(key)
                if count > 0:
                    # 查看最新的几条消息
                    messages = r.zrange(key, -5, -1, withscores=True)
                    logging.info(f"有序集合 {key} 有 {count} 条消息，最近5条:")
                    for i, (msg, score) in enumerate(messages):
                        try:
                            data = json.loads(msg)
                            time_str = datetime.fromtimestamp(score).strftime('%Y-%m-%d %H:%M:%S')
                            logging.info(f"  {i + 1}. {data.get('security', 'N/A')} - {time_str}")
                        except:
                            logging.info(f"  {i + 1}. 无法解析: {msg}")
                else:
                    logging.info(f"有序集合 {key} 为空")

            return True
        except Exception as e:
            logging.error(f"检查有序集合失败: {e}")
            return False

    def monitor_realtime(self, duration=60):
        """实时监控消息"""
        try:
            r = redis.Redis(**self.redis_config)
            pubsub = r.pubsub()
            pubsub.subscribe('jq_orders')

            logging.info(f"开始实时监控，持续时间: {duration}秒...")
            start_time = time.time()

            while time.time() - start_time < duration:
                message = pubsub.get_message(timeout=1)
                if message and message['type'] == 'message':
                    try:
                        data = json.loads(message['data'])
                        logging.info(f"收到实时消息: {data}")
                    except Exception as e:
                        logging.error(f"解析消息失败: {e}")

            pubsub.unsubscribe('jq_orders')
            logging.info("实时监控结束")

        except Exception as e:
            logging.error(f"实时监控失败: {e}")


def main():
    monitor = RedisMonitor()

    # 测试连接
    if not monitor.test_connection():
        return

    # 检查各种数据存储
    monitor.check_channels()
    monitor.check_lists()
    monitor.check_zsets()

    # 开始实时监控
    monitor.monitor_realtime(60)


if __name__ == "__main__":
    main()